package com.fanco.learn_datastruct_leetcode.juc;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author qiaowang 2021/9/9
 * 描述
 * ThreadLocal简单演示Demo
 * 可以用来处理多个客户端获取 Connectionn连接问题。
 */
public class ThreadLocalDemo {

    public static void main(String[] args) {
        ThreadLocal<String> local = new ThreadLocal<>();
        try {
            Random random = new Random();
            IntStream.range(0, 5).forEach(a -> new Thread(() -> {
                local.set(a + "   " + random.nextInt(10));
                System.out.println("线程和local值分别是" + local.get());
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start());
        } finally {
            local.remove();
        }


    }
}
